package pay.weixin;


import com.jinyou.utils.common.ValidateUtil;
import net.sf.json.JSONObject;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.sys.SysConfigPayMemory;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.sys.SysConfigPay;
import o2o.web.actions.pay.OrderPay;
import org.jdom.JDOMException;
import org.springframework.util.StringUtils;
import pay.ChannelUtils;
import pay.TradeStatusUtils;
import pay.config.WeixinConfig;
import pay.dao.QueryResult;
import pay.exceptions.DataEmptyException;
import pay.exceptions.RepeatPayExcetion;
import pay.exceptions.RequestFailException;
import pay.weixin.bean.WXPayRefund;
import pay.weixin.config.Unifiedorder;
import pay.weixin.utils.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created with IntelliJ IDEA.
 * User: Jahnke [1029777564@qq.com]
 * Date: 2017-01-07 23:53
 * 微信支付工具
 */
public class WeixinPayUtils {
    private WeixinPayUtils() {
    }

    private static WeixinPayUtils single = new WeixinPayUtils();

    public static WeixinPayUtils getInstance() {
        if (single == null) {
            single = new WeixinPayUtils();
        }
        return single;
    }

    /**
     * 微信支付二维码
     * Jahnke 2017年1月7日 23:58:29
     *
     * @param orderCode
     * @param pay
     * @param activeTime
     * @param subject
     * @param body
     * @return
     */
    public String winxin_ewm_pay(String orderCode, double pay, int activeTime, String subject, String body) throws UnsupportedEncodingException {
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", WeixinConfig.appid);
        parameters.put("mch_id", WeixinConfig.mch_id);
        parameters.put("notify_url", WeixinConfig.notify_url);
        parameters.put("body", subject == null || subject.equals("") ? "商品" : subject);
        parameters.put("nonce_str", RandCharsUtils.getRandomString(16));
        parameters.put("detail", body == null || body.equals("") ? "订单描述" : body);
        parameters.put("attach", "备用参数");
        parameters.put("out_trade_no", orderCode);
//        parameters.put("total_fee", new Float(pay * 100).intValue());        //单位是分，即是0.01元
        parameters.put("total_fee", CorrectYuan2Fen(pay));        //单位是分，即是0.01元
        String time_start = RandCharsUtils.timeStart();
        String time_expire = RandCharsUtils.timeExpire(activeTime);
        parameters.put("time_start", time_start);       //订单交易时间
        parameters.put("time_expire", time_expire);     //订单逾期时间
        String trade_type = "NATIVE";
        parameters.put("trade_type", trade_type);
        parameters.put("spbill_create_ip", "127.0.0.1");        //支付的客户端IP地址

        String sign = null;
        sign = WXSignUtils.createSign(WeixinConfig.apiKey, "UTF-8", parameters);

        Unifiedorder unifiedorder = new Unifiedorder();
        unifiedorder.setAppid(WeixinConfig.appid);
        unifiedorder.setMch_id(WeixinConfig.mch_id);
        String str = parameters.get("nonce_str").toString();
        unifiedorder.setNonce_str(str);
        unifiedorder.setSign(sign);
        unifiedorder.setBody(parameters.get("body").toString());
        unifiedorder.setDetail(parameters.get("detail").toString());
        unifiedorder.setAttach(parameters.get("attach").toString());
        unifiedorder.setOut_trade_no(orderCode);
//        unifiedorder.setTotal_fee(new Float(pay * 100).intValue());
        unifiedorder.setTotal_fee(CorrectYuan2Fen(pay));
        unifiedorder.setSpbill_create_ip(parameters.get("spbill_create_ip").toString());
        unifiedorder.setTime_start(time_start);
        unifiedorder.setTime_expire(time_expire);
        unifiedorder.setNotify_url(WeixinConfig.notify_url);
        unifiedorder.setTrade_type(trade_type);
        //构造xml参数
        String xmlInfo = null;
        //构造xml参数
//        xmlInfo = new String(HttpXmlUtils.xmlInfo(unifiedorder).getBytes("UTF-8"), "ISO-8859-1");
        xmlInfo = new String(HttpXmlUtils.xmlInfo(unifiedorder).getBytes("UTF-8"), "UTF-8");
//        xmlInfo = HttpXmlUtils.xmlInfo(unifiedorder);

        String wxUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String method = "POST";
        String weixinPost = HttpXmlUtils.httpsRequest(wxUrl, method, xmlInfo).toString();

        if (weixinPost.indexOf("<prepay_id>") <= 0) {
            return null;
        }
        if (weixinPost.indexOf("<code_url>") <= 0) {
            return null;
        }
        //生成的prepare_id二次签名
        String prepayid = weixinPost.substring(weixinPost.indexOf("<prepay_id>") + 20, weixinPost.indexOf("</prepay_id>") - 3);

        String codeUrl = weixinPost.substring(weixinPost.indexOf("<code_url>") + 19, weixinPost.indexOf("</code_url>") - 3);


        SortedMap<Object, Object> parameters02 = new TreeMap<Object, Object>();
        parameters02.put("appid", WeixinConfig.appid);
        parameters02.put("partnerid", WeixinConfig.mch_id);
        parameters02.put("package", "Sign=WXPay");
        long time = Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10));
//        System.out.println("time:" + time);
        parameters02.put("timestamp", time);
        parameters02.put("noncestr", str);
        parameters02.put("prepayid", prepayid);
        parameters02.put("codeUrl", codeUrl);
        String sign2 = WXSignUtils.createSign(WeixinConfig.apiKey, "UTF-8", parameters02);
//        System.out.println(sign2);
        parameters02.put("sign", sign2);

        return JSONObject.fromObject(parameters02).toString();
    }

    /*
     * 微信手机直接支付
     * Jahnke 2017年1月8日 08:15:19
     * @param orderCode
     * @param pay
     * @param activeTime
     * @param subject
     * @param body
     * @return
     */
    public String mobile_direct_pay(String orderCode, Double pay, int activeTime, String subject, String body)
            throws UnsupportedEncodingException, RepeatPayExcetion {
        return mobile_direct_pay(WeixinConfig.appid, WeixinConfig.mch_id, WeixinConfig.apiKey, WeixinConfig.notify_url, orderCode, pay, activeTime, subject, body);
    }

    // 骑手微信支付
    public String postman_mobile_direct_pay(String orderCode, Double pay, int activeTime, String subject, String body)
            throws UnsupportedEncodingException, RepeatPayExcetion {
        return mobile_direct_pay(WeixinConfig.qsAppid, WeixinConfig.qsMch_id, WeixinConfig.qsApiKey, WeixinConfig.notify_url, orderCode, pay, activeTime, subject, body);
    }

    // 商家微信支付
    public String shop_mobile_direct_pay(String orderCode, Double pay, int activeTime, String subject, String body)
            throws UnsupportedEncodingException, RepeatPayExcetion {
        return mobile_direct_pay(WeixinConfig.shopAppid, WeixinConfig.shopMch_id, WeixinConfig.shopApiKey, WeixinConfig.notify_url, orderCode, pay, activeTime, subject, body);
    }


    /**
     * 微信骑手端支付
     *
     * @param orderCode
     * @param pay
     * @param activeTime
     * @param subject
     * @param body
     * @return
     * @throws UnsupportedEncodingException
     * @throws RepeatPayExcetion
     */
    public String mobile_direct_pay(String appId, String mchId, String apiKey, String notify_url, String orderCode, Double pay, int activeTime, String subject, String body)
            throws UnsupportedEncodingException, RepeatPayExcetion {
        //参数：开始生成签名
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", appId);
        parameters.put("mch_id", mchId);
        parameters.put("notify_url", notify_url);
        parameters.put("body", subject == null || subject.equals("") ? "商品" : subject);
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        parameters.put("detail", body == null || body.equals("") ? "商品" : body);
        parameters.put("attach", "备用参数");
        parameters.put("out_trade_no", orderCode);
        parameters.put("total_fee", CorrectYuan2Fen(pay));        //单位是分，即是0.01元
        String time_start = RandCharsUtils.timeStart();
        String time_expire = RandCharsUtils.timeExpire(30);
        parameters.put("time_start", time_start);       //订单交易时间
        parameters.put("time_expire", time_expire);     //订单逾期时间
        String trade_type = "APP";
        parameters.put("trade_type", trade_type);
        parameters.put("spbill_create_ip", "127.0.0.1");        //支付的客户端IP地址
        String sign = WXSignUtils.createSign(apiKey, "UTF-8", parameters);

        Unifiedorder unifiedorder = new Unifiedorder();
        unifiedorder.setAppid(appId);
        unifiedorder.setAttach(parameters.get("attach").toString());
        unifiedorder.setBody(parameters.get("body").toString());
        unifiedorder.setDetail(parameters.get("detail").toString());
        unifiedorder.setMch_id(mchId);
        unifiedorder.setNonce_str(parameters.get("nonce_str").toString());
        unifiedorder.setNotify_url(notify_url);
        unifiedorder.setOut_trade_no(orderCode);
        unifiedorder.setSign(sign);
        unifiedorder.setSpbill_create_ip(parameters.get("spbill_create_ip").toString());
        unifiedorder.setTime_expire(time_expire);
        unifiedorder.setTime_start(time_start);
        unifiedorder.setTotal_fee(CorrectYuan2Fen(pay));        //单位是分，即是0.01元
        unifiedorder.setTrade_type(trade_type);
        //构造xml参数
        String xmlInfo = null;
        xmlInfo = new String(HttpXmlUtils.xmlInfo(unifiedorder).getBytes("UTF-8"), "UTF-8");
        String wxUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String method = "POST";
        String weixinPost = HttpXmlUtils.httpsRequest(wxUrl, method, xmlInfo).toString();

        if (weixinPost.indexOf("<return_code><![CDATA[FAIL]]></return_code>") >= 0) {
            System.out.println(weixinPost);
            throw new RepeatPayExcetion("获取签名失败，请稍后再试 ");
        }
        if (weixinPost.indexOf("商户订单号重复") >= 0) {
            System.out.println("商户订单号重复 " + orderCode);
            throw new RepeatPayExcetion("订单不存在");
        }
        //二次签名
        String prepayid = weixinPost.substring(weixinPost.indexOf("<prepay_id>") + 20, weixinPost.indexOf("</prepay_id>") - 3);

        SortedMap<Object, Object> parameters02 = new TreeMap<Object, Object>();
        parameters02.put("appid", appId);
        parameters02.put("partnerid", mchId);
        parameters02.put("package", "Sign=WXPay");
        long time = Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10));
        parameters02.put("timestamp", time);
        parameters02.put("noncestr", str);
        parameters02.put("prepayid", prepayid);
        String sign2 = WXSignUtils.createSign(apiKey, "UTF-8", parameters02);
        System.out.println(sign2);
        parameters02.put("sign", sign2);
        return JSONObject.fromObject(parameters02).toString();
    }

    /*
     * 公众号支付
     * Jahnke 2017年1月8日 08:15:19
     * @param orderCode
     * @param pay
     * @param activeTime
     * @param subject
     * @param body
     * @return
     */
    public String winxin_pay_gzh(String userWxOpenId, String orderCode, double pay, int activeTime, String subject, String body) throws UnsupportedEncodingException, RepeatPayExcetion {
        //参数：开始生成签名
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", WeixinConfig.gzhAppId);
        parameters.put("mch_id", WeixinConfig.gzhMchId);
        parameters.put("notify_url", WeixinConfig.gzhApiNotifyUrl);
        parameters.put("body", subject == null || subject.equals("") ? "商品" : subject);
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        parameters.put("detail", body == null || body.equals("") ? "商品" : body);
        parameters.put("attach", "备用参数");
        parameters.put("out_trade_no", orderCode);
//        parameters.put("total_fee", new Float(pay * 100).intValue());        //单位是分，即是0.01元
        parameters.put("total_fee", CorrectYuan2Fen(pay));        //单位是分，即是0.01元
        String time_start = RandCharsUtils.timeStart();
        String time_expire = RandCharsUtils.timeExpire(30);

        parameters.put("time_start", time_start);       //订单交易时间
        parameters.put("time_expire", time_expire);     //订单逾期时间
        String trade_type = "JSAPI";
        parameters.put("trade_type", trade_type);
//        parameters.put("spbill_create_ip", "127.0.0.1");        //支付的客户端IP地址
//        parameters.put("spbill_create_ip", "121.42.173.94");//支付的客户端IP地址
        parameters.put("spbill_create_ip", "127.0.0.1");        //支付的客户端IP地址
        parameters.put("openid", userWxOpenId);//openId

        String sign = WXSignUtils.createGZHSign("UTF-8", WeixinConfig.gzhApiKey, parameters);

//        System.out.println("sign：" + sign);
        Unifiedorder unifiedorder = new Unifiedorder();
        unifiedorder.setAppid(WeixinConfig.gzhAppId);
        unifiedorder.setAttach(parameters.get("attach").toString());
        unifiedorder.setBody(parameters.get("body").toString());
        unifiedorder.setDetail(parameters.get("detail").toString());
        unifiedorder.setMch_id(WeixinConfig.gzhMchId);
        unifiedorder.setNonce_str(parameters.get("nonce_str").toString());
        unifiedorder.setNotify_url(WeixinConfig.gzhApiNotifyUrl);
        unifiedorder.setOut_trade_no(orderCode);
        unifiedorder.setSign(sign);
        unifiedorder.setSpbill_create_ip(parameters.get("spbill_create_ip").toString());
        unifiedorder.setTime_expire(time_expire);
        unifiedorder.setTime_start(time_start);
//        unifiedorder.setTotal_fee(new Float(pay * 100).intValue());
        unifiedorder.setTotal_fee(CorrectYuan2Fen(pay));
        unifiedorder.setTrade_type(trade_type);
        unifiedorder.setOpenid(userWxOpenId);

        //构造xml参数
        String xmlInfo = null;
        xmlInfo = new String(HttpXmlUtils.getGZHXmlInfo(unifiedorder).getBytes("UTF-8"), "UTF-8");

//        System.out.println("xml：" + xmlInfo);

        String wxUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String method = "POST";
        String weixinPost = HttpXmlUtils.httpsRequest(wxUrl, method, xmlInfo).toString();
        System.out.println(weixinPost);
        if (weixinPost.indexOf("<return_code><![CDATA[FAIL]]></return_code>") >= 0) {
            return weixinPost.substring(weixinPost.indexOf("<return_msg><![CDATA[") + 21, weixinPost.indexOf("]]></return_msg>"));
        }
        if (weixinPost.indexOf("商户订单号重复") >= 0) {
            throw new RepeatPayExcetion("订单不存在");
        }
        //二次签名
        String prepayid = weixinPost.substring(weixinPost.indexOf("<prepay_id>") + 20, weixinPost.indexOf("</prepay_id>") - 3);

        SortedMap<Object, Object> parameters02 = new TreeMap<Object, Object>();
        parameters02.put("appId", WeixinConfig.gzhAppId);
//        parameters02.put("partnerid", WeixinConfig.mch_id);
//        parameters02.put("package", "Sign=WXPay");
        parameters02.put("package", "prepay_id=" + prepayid);
        long time = Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10));
//        System.out.println("time:" + time);
        parameters02.put("timeStamp", "" + time);
        parameters02.put("nonceStr", str);
        parameters02.put("signType", "MD5");
//        parameters02.put("total_fee", parameters.get("total_fee").toString());
//        parameters02.put("prepayid", prepayid);
        String sign2 = WXSignUtils.createSign(WeixinConfig.apiKey, "UTF-8", parameters02);
        parameters02.put("paySign", sign2);
//        parameters02.put("paySign", sign);
//        System.out.println("sign(WX):" + JSONObject.fromObject(parameters02).toString());
        return JSONObject.fromObject(parameters02).toString();
    }


    /*
     * 小程序支付
     * Jahnke 2017年1月8日 08:15:19
     * @param orderCode
     * @param pay
     * @param activeTime
     * @param subject
     * @param body
     * @return
     */
    public String winxin_pay_xcx(String sysAppKey, String appFlag, String userWxOpenId, String orderCode, double pay, int activeTime, String subject, String body) {
        String xcxAppId = WeixinConfig.xcxAppId;
        String xcxMchId = WeixinConfig.xcxMchId;
        String xcxNotifyUrl = WeixinConfig.xcxApiNotifyUrl;
        String xcxApiKey = WeixinConfig.xcxApiKey;
        if (ValidateUtil.isNotNull(appFlag)) {
            SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByKey(sysAppKey, appFlag);
            if (null != sysConfigPay) {
                xcxAppId = sysConfigPay.getWxXcxAppId();
                xcxMchId = sysConfigPay.getWxXcxMchId();
                xcxNotifyUrl = sysConfigPay.getWxXcxApiNotifyUrl();
                xcxApiKey = sysConfigPay.getWxXcxApiKey();
            }
        }

        return winxin_pay_xcx(userWxOpenId, orderCode, pay, activeTime, subject, body,
                xcxAppId, xcxMchId, xcxApiKey, xcxNotifyUrl);
    }

//    public String winxin_pay_xcx(String userWxOpenId, String orderCode, double pay, int activeTime, String subject, String body) {
//        String xcxAppId = WeixinConfig.xcxAppId;
//        String xcxMchId = WeixinConfig.xcxMchId;
//        String xcxNotifyUrl = WeixinConfig.xcxApiNotifyUrl;
//        String xcxApiKey = WeixinConfig.xcxApiKey;
//        return winxin_pay_xcx(userWxOpenId, orderCode, pay, activeTime, subject, body,
//                xcxAppId, xcxMchId, xcxApiKey, xcxNotifyUrl);
//    }

    public String winxin_pay_xcx(String userWxOpenId, String orderCode, double pay, int activeTime, String subject, String body,
                                 String xcxAppId, String xcxMchId, String xcxApiKey, String xcxNotifyUrl) {
        //参数：开始生成签名
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", xcxAppId);
        parameters.put("mch_id", xcxMchId);
        parameters.put("notify_url", xcxNotifyUrl);
        parameters.put("body", subject == null || subject.equals("") ? "商品" : subject);
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        parameters.put("detail", body == null || body.equals("") ? "商品" : body);
        parameters.put("attach", "备用参数");
        parameters.put("out_trade_no", orderCode);
//        parameters.put("total_fee", new Float(pay * 100).intValue());        //单位是分，即是0.01元
        parameters.put("total_fee", CorrectYuan2Fen(pay));        //单位是分，即是0.01元
        String time_start = RandCharsUtils.timeStart();
        String time_expire = RandCharsUtils.timeExpire(30);

        parameters.put("time_start", time_start);       //订单交易时间
        parameters.put("time_expire", time_expire);     //订单逾期时间
        String trade_type = "JSAPI";
        parameters.put("trade_type", trade_type);
//        parameters.put("spbill_create_ip", "127.0.0.1");        //支付的客户端IP地址
//        parameters.put("spbill_create_ip", "121.42.173.94");//支付的客户端IP地址
        parameters.put("spbill_create_ip", "127.0.0.1");        //支付的客户端IP地址
        parameters.put("openid", userWxOpenId);//openId

        String sign = WXSignUtils.createXCXSign("UTF-8", xcxApiKey, parameters);

//        System.out.println("sign：" + sign);
        Unifiedorder unifiedorder = new Unifiedorder();
        unifiedorder.setAppid(xcxAppId);
        unifiedorder.setAttach(parameters.get("attach").toString());
        unifiedorder.setBody(parameters.get("body").toString());
        unifiedorder.setDetail(parameters.get("detail").toString());
        unifiedorder.setMch_id(xcxMchId);
        unifiedorder.setNonce_str(parameters.get("nonce_str").toString());
        unifiedorder.setNotify_url(xcxNotifyUrl);
        unifiedorder.setOut_trade_no(orderCode);
        unifiedorder.setSign(sign);
        unifiedorder.setSpbill_create_ip(parameters.get("spbill_create_ip").toString());
        unifiedorder.setTime_expire(time_expire);
        unifiedorder.setTime_start(time_start);
//        unifiedorder.setTotal_fee(new Float(pay * 100).intValue());
        unifiedorder.setTotal_fee(CorrectYuan2Fen(pay));
        unifiedorder.setTrade_type(trade_type);
        unifiedorder.setOpenid(userWxOpenId);

        //构造xml参数
        String xmlInfo = null;
        try {
            xmlInfo = new String(HttpXmlUtils.getGZHXmlInfo(unifiedorder).getBytes("UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

//        System.out.println("xml：" + xmlInfo);

        String wxUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String method = "POST";
        String weixinPost = HttpXmlUtils.httpsRequest(wxUrl, method, xmlInfo).toString();
        System.out.println(weixinPost);
        if (weixinPost.indexOf("<return_code><![CDATA[FAIL]]></return_code>") >= 0) {
            return weixinPost.substring(weixinPost.indexOf("<return_msg><![CDATA[") + 21, weixinPost.indexOf("]]></return_msg>"));
        }
        if (weixinPost.indexOf("商户订单号重复") >= 0) {
            System.out.println("订单支付失败，商户订单好重复，" + orderCode);
        }
        //二次签名
        String prepayid = weixinPost.substring(weixinPost.indexOf("<prepay_id>") + 20, weixinPost.indexOf("</prepay_id>") - 3);

        SortedMap<Object, Object> parameters02 = new TreeMap<Object, Object>();
        parameters02.put("appId", xcxAppId);
//        parameters02.put("partnerid", WeixinConfig.mch_id);
//        parameters02.put("package", "Sign=WXPay");
        parameters02.put("package", "prepay_id=" + prepayid);
        long time = Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10));
//        System.out.println("time:" + time);
        parameters02.put("timeStamp", "" + time);
        parameters02.put("nonceStr", str);
        parameters02.put("signType", "MD5");
//        parameters02.put("total_fee", parameters.get("total_fee").toString());
//        parameters02.put("prepayid", prepayid);
        String sign2 = WXSignUtils.createXCXSign("UTF-8", xcxApiKey, parameters02);
        parameters02.put("paySign", sign2);
//        parameters02.put("paySign", sign);
//        System.out.println("sign(WX):" + JSONObject.fromObject(parameters02).toString());
        return JSONObject.fromObject(parameters02).toString();
    }


    /*
     * H5 支付
     */
    public String winxin_pay_wap(String orderCode, double pay, int activeTime, String subject, String body) {
        //参数：开始生成签名
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", WeixinConfig.gzhAppId);
        parameters.put("mch_id", WeixinConfig.gzhMchId);
        parameters.put("notify_url", WeixinConfig.gzhApiNotifyUrl);
        parameters.put("body", subject == null || subject.equals("") ? "商品" : subject);
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        parameters.put("detail", body == null || body.equals("") ? "商品" : body);
        parameters.put("attach", "备用参数");
        parameters.put("out_trade_no", orderCode);
//        parameters.put("total_fee", new Float(pay * 100).intValue());        //单位是分，即是0.01元
        parameters.put("total_fee", CorrectYuan2Fen(pay));        //单位是分，即是0.01元
        String time_start = RandCharsUtils.timeStart();
        String time_expire = RandCharsUtils.timeExpire(30);

        parameters.put("time_start", time_start);       //订单交易时间
        parameters.put("time_expire", time_expire);     //订单逾期时间
        String trade_type = "MWEB";
        parameters.put("trade_type", trade_type);
//        parameters.put("spbill_create_ip", "127.0.0.1");        //支付的客户端IP地址
//        parameters.put("spbill_create_ip", "121.42.173.94");//支付的客户端IP地址
        parameters.put("spbill_create_ip", "127.0.0.1");        //支付的客户端IP地址
//        parameters.put("openid", userWxOpenId);//openId

        String sign = WXSignUtils.createWapSign("UTF-8", parameters);

//        System.out.println("sign：" + sign);
        Unifiedorder unifiedorder = new Unifiedorder();
        unifiedorder.setAppid(WeixinConfig.gzhAppId);
        unifiedorder.setAttach(parameters.get("attach").toString());
        unifiedorder.setBody(parameters.get("body").toString());
        unifiedorder.setDetail(parameters.get("detail").toString());
        unifiedorder.setMch_id(WeixinConfig.gzhMchId);
        unifiedorder.setNonce_str(parameters.get("nonce_str").toString());
        unifiedorder.setNotify_url(WeixinConfig.gzhApiNotifyUrl);
        unifiedorder.setOut_trade_no(orderCode);
        unifiedorder.setSign(sign);
        unifiedorder.setSpbill_create_ip(parameters.get("spbill_create_ip").toString());
        unifiedorder.setTime_expire(time_expire);
        unifiedorder.setTime_start(time_start);
//        unifiedorder.setTotal_fee(new Float(pay * 100).intValue());
        unifiedorder.setTotal_fee(CorrectYuan2Fen(pay));
        unifiedorder.setTrade_type(trade_type);
//        unifiedorder.setOpenid(userWxOpenId);

        //构造xml参数
        String xmlInfo = null;
        try {
            xmlInfo = new String(HttpXmlUtils.getGZHXmlInfo(unifiedorder).getBytes("UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

//        System.out.println("xml：" + xmlInfo);

        String wxUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String method = "POST";
        String weixinPost = HttpXmlUtils.httpsRequest(wxUrl, method, xmlInfo).toString();
        System.out.println(weixinPost);
        if (weixinPost.indexOf("<return_code><![CDATA[FAIL]]></return_code>") >= 0) {
            return weixinPost.substring(weixinPost.indexOf("<return_msg><![CDATA[") + 21, weixinPost.indexOf("]]></return_msg>"));
        }
        if (weixinPost.indexOf("商户订单号重复") >= 0) {
            System.out.println("商户订单号重复");
            return null;
        }
        //二次签名
        String prepayid = weixinPost.substring(weixinPost.indexOf("<prepay_id>") + 20, weixinPost.indexOf("</prepay_id>") - 3);

        SortedMap<Object, Object> parameters02 = new TreeMap<Object, Object>();
        parameters02.put("appId", WeixinConfig.gzhAppId);
//        parameters02.put("partnerid", WeixinConfig.mch_id);
//        parameters02.put("package", "Sign=WXPay");
        parameters02.put("package", "prepay_id=" + prepayid);
        long time = Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10));
//        System.out.println("time:" + time);
        parameters02.put("timeStamp", "" + time);
        parameters02.put("nonceStr", str);
        parameters02.put("signType", "MD5");
//        parameters02.put("total_fee", parameters.get("total_fee").toString());
//        parameters02.put("prepayid", prepayid);
        String sign2 = null;

        sign2 = WXSignUtils.createWapSign("UTF-8", parameters02);

        parameters02.put("paySign", sign2);
//        parameters02.put("paySign", sign);
//        System.out.println("sign(WX):" + JSONObject.fromObject(parameters02).toString());
        return JSONObject.fromObject(parameters02).toString();
    }


    //微信查询订单状态
//    public String query_pay_trade(String payOrderNo, String orderNo) throws IOException, JDOMException, DataEmptyException {
//        String url = "https://api.mch.weixin.qq.com/pay/orderquery";
//
//        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
//        map.put("appid", WeixinConfig.appid);
//        map.put("mch_id", WeixinConfig.mch_id);
//        if (payOrderNo != null && !payOrderNo.equals("")) {
//            map.put("transaction_id", payOrderNo);
//        }
//        map.put("out_trade_no", orderNo);
//
//        // 生成签名
//        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
//        parameters.put("appid", WeixinConfig.appid);
//        parameters.put("mch_id", WeixinConfig.mch_id);
//        String str = RandCharsUtils.getRandomString(16);
//        parameters.put("nonce_str", str);
//        parameters.put("out_trade_no", orderNo);
//        String sign = WXSignUtils.createSign("UTF-8", parameters);      //签名
//
//        map.put("nonce_str", str);
//        map.put("sign", sign);
//        String method = "POST";
//        String json = HttpXmlUtils.httpsRequest(url, method, HttpXmlUtils.toQueryXml(map)).toString();
//        Map<String, Object> mdata = XMLUtils.doXMLParse(json);
//       /* if (mdata != null && mdata.size() > 0) {
//            for (String key : mdata.keySet()) {
//                System.out.println(key + ":" + mdata.get(key));
//            }
//        }*/
//        if (null == mdata) {
//            return null;
//        }
//        String err_code = mdata.containsKey("err_code") ? mdata.get("err_code").toString() : "";
//        if (err_code.indexOf("ORDERNOTEXIST") >= 0) {
//            throw new DataEmptyException("订单不存在");
//        } else if (err_code.indexOf("SYSTEMERROR") >= 0) {
//            throw new DataEmptyException("系统异常，请再调用发起查询");
//        }
//        String trade_state = mdata.get("trade_state").toString();
//        if (trade_state.equals("SUCCESS")) {
//            return TradeStatusUtils.TRADE_SUCCESS;
//        } else if (trade_state.equals("NOTPAY")) {
//            return TradeStatusUtils.TRADE_CLOSED;
//        } else if (trade_state.equals("CLOSED")) {
//            return TradeStatusUtils.TRADE_CLOSED;
//        } else if (trade_state.equals("USERPAYING")) {
//            return TradeStatusUtils.Trade_USERPAYING;
//        } else if (trade_state.equals("PAYERROR")) {
//            return TradeStatusUtils.TRADE_PAYERROR;
//        } else if (trade_state.equals("REFUND")) {
//            return TradeStatusUtils.TRADE_REFUND;
//        }
//        return "";
//    }

    //微信查询订单状态
    public QueryResult getWxPayStatus(String appFlag, String payOrderNo, String channel, Integer userType, String orderNo) {
        String url = "https://api.mch.weixin.qq.com/pay/orderquery";

        OrderInfo orderInfo = null;

        String appId = WeixinConfig.appid;
        String mch_id = WeixinConfig.mch_id;
        String apiKey = WeixinConfig.apiKey;
        if (null != userType) {
            switch (userType) {
                case UserType.SHOP_OWNER: {
                    appId = WeixinConfig.shopAppid;
                    mch_id = WeixinConfig.shopMch_id;
                    apiKey = WeixinConfig.shopApiKey;
                }
                break;
                case UserType.POSTMAN: {
                    appId = WeixinConfig.qsAppid;
                    mch_id = WeixinConfig.qsMch_id;
                    apiKey = WeixinConfig.qsApiKey;
                }
                break;
                default: {
//                    appId = WeixinConfig.appid;
//                    mch_id = WeixinConfig.mch_id;
                }
                break;
            }
        }
        if (channel.equals(ChannelUtils.wx_pub_qr) || channel.equals(ChannelUtils.wx_gzh)) {
            appId = WeixinConfig.gzhAppId;
            mch_id = WeixinConfig.gzhMchId;
        } else if (channel.equals(ChannelUtils.wx_xcx)) {
            appId = WeixinConfig.xcxAppId;
            mch_id = WeixinConfig.xcxMchId;

            orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            if (null != orderInfo && ValidateUtil.isID(orderInfo.getAgentId())) {
                SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByAgentId(orderInfo.getAgentId(), appFlag);
                if (null != sysConfigPay && ValidateUtil.isNotNull(sysConfigPay.getWxXcxApiKey())) {
                    appId = sysConfigPay.getWxXcxAppId();
                    mch_id = sysConfigPay.getWxXcxMchId();
                }
            }
        }

        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("appid", appId);
        map.put("mch_id", mch_id);
        if (payOrderNo != null && !payOrderNo.equals("")) {
            map.put("transaction_id", payOrderNo);
        }
        map.put("out_trade_no", orderNo);

        QueryResult queryResult = new QueryResult();
        // 生成签名
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", appId);
        parameters.put("mch_id", mch_id);
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        parameters.put("out_trade_no", orderNo);
        String sign = null;      //签名

//        try {
//            sign = WXSignUtils.createSign("UTF-8", parameters);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
//            return queryResult;
//        }
//
        if (channel.equals(ChannelUtils.wx)) {
            try {
                sign = WXSignUtils.createSign(apiKey, "UTF-8", parameters);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                queryResult.setError("查询失败微信支付，创建签名失败");
                return queryResult;
            }
        } else if (channel.equals(ChannelUtils.wx_pub_qr) || channel.equals(ChannelUtils.wx_gzh)) {
            try {
                sign = WXSignUtils.createGZHSign("UTF-8", WeixinConfig.gzhApiKey, parameters);
            } catch (Exception e) {
                e.printStackTrace();
                queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                queryResult.setError("查询失败微信公众号支付，创建签名失败");
                return queryResult;
            }
        } else if (channel.equals(ChannelUtils.wx_xcx)) {
            String wxXcxAppKey = WeixinConfig.xcxApiKey;
            orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            if (null != orderInfo && ValidateUtil.isID(orderInfo.getAgentId())) {
                SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByAgentId(orderInfo.getAgentId(), appFlag);
                if (null != sysConfigPay && ValidateUtil.isNotNull(sysConfigPay.getWxXcxApiKey())) {
                    wxXcxAppKey = sysConfigPay.getWxXcxApiKey();
                }
            }
            try {
                sign = WXSignUtils.createXCXSign("UTF-8", wxXcxAppKey, parameters);
            } catch (Exception e) {
                e.printStackTrace();
                queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                queryResult.setError("查询失败微信小程序支付，创建签名失败");
                return queryResult;
            }
        }


        map.put("nonce_str", str);
        map.put("sign", sign);
        String method = "POST";
        String json = HttpXmlUtils.httpsRequest(url, method, HttpXmlUtils.toQueryXml(map)).toString();
        Map<String, Object> mdata = null;
        try {
            mdata = XMLUtils.doXMLParse(json);
        } catch (JDOMException e) {
            e.printStackTrace();
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        } catch (IOException e) {
            e.printStackTrace();
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        if (null == mdata) {
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        if ("FAIL".equalsIgnoreCase(mdata.get("return_code").toString())) {
            System.out.println("查询微信支付错误：" + mdata.get("return_code").toString() + "," + mdata.get("return_msg").toString());
            queryResult.setQuerySuccess(true);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        String err_code = mdata.containsKey("err_code") ? mdata.get("err_code").toString() : "";
        if (err_code.indexOf("ORDERNOTEXIST") >= 0) {
            queryResult.setQuerySuccess(true);
            queryResult.setPayStatus(TradeStatusUtils.ORDER_NOT_EXIST);
            return queryResult;
//            throw new DataEmptyException("订单不存在");
        } else if (err_code.indexOf("SYSTEMERROR") >= 0) {
            queryResult.setQuerySuccess(true);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            queryResult.setError("系统异常，请再调用发起查询");
            return queryResult;
//            throw new DataEmptyException("系统异常，请再调用发起查询");
        }

        String trade_state = mdata.get("trade_state").toString();
        if (ValidateUtil.isNotNull(trade_state)) {
            queryResult.setQuerySuccess(true);
            switch (trade_state) {
                case "SUCCESS": {
                    queryResult.setPaySuccess(true);
                    queryResult.setPayerId(mdata.get("openid").toString());
//                    queryResult.setPayerAccount(mdata.get("openid").toString());
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_SUCCESS);
                }
                break;
                case "NOTPAY": {
                    queryResult.setPayStatus(TradeStatusUtils.NOT_PAY);
                }
                break;
                case "CLOSED": {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_CLOSED);
                }
                break;
                case "USERPAYING": {
                    queryResult.setPayStatus(TradeStatusUtils.Trade_USERPAYING);
                }
                break;
                case "PAYERROR": {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                }
                break;
                case "REFUND": {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_REFUND);
                }
                break;
                default: {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                }
                break;
            }
        } else {
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
        }

        return queryResult;
    }

    // ------------------查询

    /**
     * 微信查询订单状态
     */
    public QueryResult getWxPayStatus(String appId, String mch_id, String apiKey,
                                      String payOrderNo, String channel,
                                      String orderNo) {
        String url = "https://api.mch.weixin.qq.com/pay/orderquery";

//        OrderInfo orderInfo = null;

//        String appId = WeixinConfig.appid;
//        String mch_id = WeixinConfig.mch_id;
//        String apiKey = WeixinConfig.apiKey;
//        if (null != userType) {
//            switch (userType) {
//                case UserType.SHOP_OWNER: {
//                    appId = WeixinConfig.shopAppid;
//                    mch_id = WeixinConfig.shopMch_id;
//                    apiKey = WeixinConfig.shopApiKey;
//                }
//                break;
//                case UserType.POSTMAN: {
//                    appId = WeixinConfig.qsAppid;
//                    mch_id = WeixinConfig.qsMch_id;
//                    apiKey = WeixinConfig.qsApiKey;
//                }
//                break;
//                default: {
////                    appId = WeixinConfig.appid;
////                    mch_id = WeixinConfig.mch_id;
//                }
//                break;
//            }
//        }
//        if (channel.equals(ChannelUtils.wx_pub_qr) || channel.equals(ChannelUtils.wx_gzh)) {
//            appId = WeixinConfig.gzhAppId;
//            mch_id = WeixinConfig.gzhMchId;
//        } else if (channel.equals(ChannelUtils.wx_xcx)) {
//            appId = WeixinConfig.xcxAppId;
//            mch_id = WeixinConfig.xcxMchId;
//
//            orderInfo = OrderInfoMemory.getInstance().getOrderInfo(sysAppKey, orderNo);
//            if (null != orderInfo && ValidateUtil.isID(orderInfo.getAgentId())) {
//                SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByAgentId(orderInfo.getSysAppKey(), orderInfo.getAgentId());
//                if (null != sysConfigPay && ValidateUtil.isNotNull(sysConfigPay.getWxXcxApiKey())) {
//                    appId = sysConfigPay.getWxXcxAppId();
//                    mch_id = sysConfigPay.getWxXcxMchId();
//                }
//            }
//        }

        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("appid", appId);
        map.put("mch_id", mch_id);
        if (payOrderNo != null && !payOrderNo.equals("")) {
            map.put("transaction_id", payOrderNo);
        }
        map.put("out_trade_no", orderNo);

        QueryResult queryResult = new QueryResult();
        // 生成签名
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", appId);
        parameters.put("mch_id", mch_id);
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        parameters.put("out_trade_no", orderNo);
        String sign = null;      //签名

        if (channel.equals(ChannelUtils.wx)) {
            try {
                sign = WXSignUtils.createSign(apiKey, "UTF-8", parameters);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                queryResult.setError("查询失败微信支付，创建签名失败");
                return queryResult;
            }
        } else if (channel.equals(ChannelUtils.wx_pub_qr) || channel.equals(ChannelUtils.wx_gzh)) {
            try {
                sign = WXSignUtils.createGZHSign("UTF-8", apiKey, parameters);
            } catch (Exception e) {
                e.printStackTrace();
                queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                queryResult.setError("查询失败微信公众号支付，创建签名失败");
                return queryResult;
            }
        } else if (channel.equals(ChannelUtils.wx_xcx)) {
//            String wxXcxAppKey = WeixinConfig.xcxApiKey;
//            orderInfo = OrderInfoMemory.getInstance().getOrderInfo(sysAppKey, orderNo);
//            if (null != orderInfo && ValidateUtil.isID(orderInfo.getAgentId())) {
//                SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByAgentId(orderInfo.getSysAppKey(), orderInfo.getAgentId());
//                if (null != sysConfigPay && ValidateUtil.isNotNull(sysConfigPay.getWxXcxApiKey())) {
//                    wxXcxAppKey = sysConfigPay.getWxXcxApiKey();
//                }
//            }
            try {
                sign = WXSignUtils.createXCXSign("UTF-8", apiKey, parameters);
            } catch (Exception e) {
                e.printStackTrace();
                queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                queryResult.setError("查询失败微信小程序支付，创建签名失败");
                return queryResult;
            }
        }


        map.put("nonce_str", str);
        map.put("sign", sign);
        String method = "POST";
        String json = HttpXmlUtils.httpsRequest(url, method, HttpXmlUtils.toQueryXml(map)).toString();
        Map<String, Object> mdata = null;
        try {
            mdata = XMLUtils.doXMLParse(json);
        } catch (JDOMException e) {
            e.printStackTrace();
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        } catch (IOException e) {
            e.printStackTrace();
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        if (null == mdata) {
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        if ("FAIL".equalsIgnoreCase(mdata.get("return_code").toString())) {
            System.out.println("查询微信支付错误：" + mdata.get("return_code").toString() + "," + mdata.get("return_msg").toString());
            queryResult.setQuerySuccess(true);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        String err_code = mdata.containsKey("err_code") ? mdata.get("err_code").toString() : "";
        if (err_code.indexOf("ORDERNOTEXIST") >= 0) {
            queryResult.setQuerySuccess(true);
            queryResult.setPayStatus(TradeStatusUtils.ORDER_NOT_EXIST);
            return queryResult;
//            throw new DataEmptyException("订单不存在");
        } else if (err_code.indexOf("SYSTEMERROR") >= 0) {
            queryResult.setQuerySuccess(true);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            queryResult.setError("系统异常，请再调用发起查询");
            return queryResult;
//            throw new DataEmptyException("系统异常，请再调用发起查询");
        }

        String trade_state = mdata.get("trade_state").toString();
        if (ValidateUtil.isNotNull(trade_state)) {
            queryResult.setQuerySuccess(true);
            switch (trade_state) {
                case "SUCCESS": {
                    queryResult.setPaySuccess(true);
                    queryResult.setPayerId(mdata.get("openid").toString());
//                    queryResult.setPayerAccount(mdata.get("openid").toString());
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_SUCCESS);
                }
                break;
                case "NOTPAY": {
                    queryResult.setPayStatus(TradeStatusUtils.NOT_PAY);
                }
                break;
                case "CLOSED": {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_CLOSED);
                }
                break;
                case "USERPAYING": {
                    queryResult.setPayStatus(TradeStatusUtils.Trade_USERPAYING);
                }
                break;
                case "PAYERROR": {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                }
                break;
                case "REFUND": {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_REFUND);
                }
                break;
                default: {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                }
                break;
            }
        } else {
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
        }

        return queryResult;
    }


    //骑手端 微信查询订单状态
    public QueryResult getQsWxPayStatus(String payOrderNo, String channel, String orderNo) {
        String url = "https://api.mch.weixin.qq.com/pay/orderquery";
        OrderInfo orderInfo = null;
        String appId = WeixinConfig.qsAppid;
        String mch_id = WeixinConfig.qsMch_id;
//        if (channel.equals(ChannelUtils.wx_pub_qr) || channel.equals(ChannelUtils.wx_gzh)) {
//            appId = WeixinConfig.gzhAppId;
//            mch_id = WeixinConfig.gzhMchId;
//        } else if (channel.equals(ChannelUtils.wx_xcx)) {
//            appId = WeixinConfig.xcxAppId;
//            mch_id = WeixinConfig.xcxMchId;
//
//            orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
//            if (null != orderInfo && ValidateUtil.isID(orderInfo.getAgentId())) {
//                SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByAgentId(orderInfo.getAgentId());
//                if (null != sysConfigPay && ValidateUtil.isNotNull(sysConfigPay.getWxXcxApiKey())) {
//                    appId = sysConfigPay.getWxXcxAppId();
//                    mch_id = sysConfigPay.getWxXcxMchId();
//                }
//            }
//        }

        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("appid", appId);
        map.put("mch_id", mch_id);
        if (payOrderNo != null && !payOrderNo.equals("")) {
            map.put("transaction_id", payOrderNo);
        }
        map.put("out_trade_no", orderNo);

        QueryResult queryResult = new QueryResult();
        // 生成签名
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", appId);
        parameters.put("mch_id", mch_id);
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        parameters.put("out_trade_no", orderNo);
        String sign = null;      //签名
        if (channel.equals(ChannelUtils.wx)) {
            try {
                sign = WXSignUtils.createSign(WeixinConfig.qsApiKey, "UTF-8", parameters);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                queryResult.setError("查询失败微信支付，创建签名失败");
                return queryResult;
            }
        }
//        else if (channel.equals(ChannelUtils.wx_pub_qr) || channel.equals(ChannelUtils.wx_gzh)) {
//            try {
//                sign = WXSignUtils.createGZHSign("UTF-8", parameters);
//            } catch (Exception e) {
//                e.printStackTrace();
//                queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
//                queryResult.setError("查询失败微信公众号支付，创建签名失败");
//                return queryResult;
//            }
//        } else if (channel.equals(ChannelUtils.wx_xcx)) {
//            String wxXcxAppKey = WeixinConfig.xcxApiKey;
//            orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
//            if (null != orderInfo && ValidateUtil.isID(orderInfo.getAgentId())) {
//                SysConfigPay sysConfigPay = SysConfigPayMemory.getInstance().getByAgentId(orderInfo.getAgentId());
//                if (null != sysConfigPay && ValidateUtil.isNotNull(sysConfigPay.getWxXcxApiKey())) {
//                    wxXcxAppKey = sysConfigPay.getWxXcxApiKey();
//                }
//            }
//            try {
//                sign = WXSignUtils.createXCXSign("UTF-8", wxXcxAppKey, parameters);
//            } catch (Exception e) {
//                e.printStackTrace();
//                queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
//                queryResult.setError("查询失败微信小程序支付，创建签名失败");
//                return queryResult;
//            }
//        }


        map.put("nonce_str", str);
        map.put("sign", sign);
        String method = "POST";
        String json = HttpXmlUtils.httpsRequest(url, method, HttpXmlUtils.toQueryXml(map)).toString();
        Map<String, Object> mdata = null;
        try {
            mdata = XMLUtils.doXMLParse(json);
        } catch (JDOMException e) {
            e.printStackTrace();
            System.out.println("a");
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("b");
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        if (null == mdata) {
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            System.out.println("c");
            return queryResult;
        }

        if ("FAIL".equalsIgnoreCase(mdata.get("return_code").toString())) {
            System.out.println("查询微信支付错误：" + mdata.get("return_code").toString() + "," + mdata.get("return_msg").toString());
            queryResult.setQuerySuccess(true);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        String err_code = mdata.containsKey("err_code") ? mdata.get("err_code").toString() : "";
        if (err_code.indexOf("ORDERNOTEXIST") >= 0) {
            queryResult.setQuerySuccess(true);
            queryResult.setPayStatus(TradeStatusUtils.ORDER_NOT_EXIST);
            System.out.println("d");
            return queryResult;
//            throw new DataEmptyException("订单不存在");
        } else if (err_code.indexOf("SYSTEMERROR") >= 0) {
            queryResult.setQuerySuccess(true);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            queryResult.setError("系统异常，请再调用发起查询");
            System.out.println("e");
            return queryResult;
//            throw new DataEmptyException("系统异常，请再调用发起查询");
        }

        String trade_state = mdata.get("trade_state").toString();
        if (ValidateUtil.isNotNull(trade_state)) {
            queryResult.setQuerySuccess(true);
            switch (trade_state) {
                case "SUCCESS": {
                    System.out.println("e");
                    queryResult.setPaySuccess(true);
                    queryResult.setPayerId(mdata.get("openid").toString());
//                    queryResult.setPayerAccount(mdata.get("openid").toString());
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_SUCCESS);
                }
                break;
                case "NOTPAY": {
                    queryResult.setPayStatus(TradeStatusUtils.NOT_PAY);
                }
                break;
                case "CLOSED": {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_CLOSED);
                }
                break;
                case "USERPAYING": {
                    queryResult.setPayStatus(TradeStatusUtils.Trade_USERPAYING);
                }
                break;
                case "PAYERROR": {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                }
                break;
                case "REFUND": {
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_REFUND);
                }
                break;
                default: {
                    System.out.println("f");
                    queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
                }
                break;
            }
        } else {
            System.out.println("g");
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
        }

        return queryResult;
    }


    public static boolean refund(String appid, String mch_id, String apiKey,
                                 String certFilePath,
                                 String orderNo, String fcOrderNo, double money, double refundMoney) throws RequestFailException, DataEmptyException {
        String result = "";
        if (StringUtils.isEmpty(result)) {
//            String appid = WeixinConfig.appid;
//            String mch_id = WeixinConfig.mch_id;
//            String apiKey = WeixinConfig.apiKey;


            String nonce_str = RandCharsUtils.getRandomString(32);
            String out_refund_no = "T" + orderNo;
//            int total_fee = (int) (money * 100);//单位为分
//            int refund_fee = (int) (refundMoney * 100);
//            int total_fee = new Float(money * 100).intValue();//单位是分，即是0.01元
//            int refund_fee = new Float(money * 100).intValue();

            int total_fee = CorrectYuan2Fen(money);//单位是分，即是0.01元
            int refund_fee = CorrectYuan2Fen(money);

            String op_user_id = mch_id;//操作员帐号, 默认为商户号

            SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
            parameters.put("appid", appid);
            parameters.put("mch_id", mch_id);
            parameters.put("nonce_str", nonce_str);
            parameters.put("out_trade_no", orderNo);
            parameters.put("out_refund_no", out_refund_no);
            parameters.put("total_fee", total_fee);
            parameters.put("refund_fee", refund_fee);
            parameters.put("op_user_id", op_user_id);

            String sign = WXSignUtils.createRefundSign(apiKey, "UTF-8", parameters);
            System.out.println("签名是：" + sign);

            WXPayRefund refund = new WXPayRefund();
            refund.setAppid(appid);
            refund.setMch_id(mch_id);
            refund.setNonce_str(nonce_str);
            refund.setOp_user_id(op_user_id);
            refund.setOut_refund_no(out_refund_no);
            refund.setRefund_fee(refund_fee);
            refund.setSign(sign);
            refund.setTotal_fee(total_fee);
            refund.setOut_trade_no(orderNo);

            //构造xml参数
            String xmlInfo = HttpXmlUtils.getRefundXmlInfo(refund);
//            System.out.println("xml是：" + xmlInfo);
            String wxUrl = WeixinConfig.refund_URL;
            String weixinPost = null;
//            String certFilePath = WeixinConfig.wx_refund_cert_file_path;
            try {
                weixinPost = ClientCustomSSL.doRefund(wxUrl, xmlInfo, certFilePath, mch_id).toString();
            } catch (Exception e) {
                System.out.println("微信退款失败：" + e.getMessage());
                e.printStackTrace();
                return false;
            }
            System.out.println("微信退款：" + weixinPost);

            if (weixinPost.indexOf("<return_code><![CDATA[FAIL]]></return_code>") >= 0) {
                System.out.println(weixinPost);
                throw new RequestFailException("申请退款失败，请稍后再试 ");
            }
            if (weixinPost.indexOf("<result_code><![CDATA[FAIL]]></result_code>") >= 0) {
//                System.out.println("退款失败：" + weixinPost);
                try {
                    if (weixinPost.indexOf("<err_code_des><![CDATA[") >= 0) {
                        String msg = weixinPost.substring(weixinPost.indexOf("<err_code_des><![CDATA[") + 23, weixinPost.indexOf("]]></err_code_des>"));
                        throw new RequestFailException("订单：" + orderNo + "申请退款失败:" + msg);
                    }
                } catch (Exception e) {
                    System.out.println("截取退款失败原因失败" + e.getMessage());
//                    e.printStackTrace();
                }
                throw new RequestFailException("申请退款失败，请稍后再试！");
            }
            if (weixinPost.indexOf("ORDERNOTEXIST") >= 0 && weixinPost.indexOf("订单不存在") >= 0) {
                throw new DataEmptyException("订单不存在");
            }
            try {
                if (weixinPost.indexOf("<refund_id><![CDATA[") >= 0) {
                    String refund_id = weixinPost.substring(weixinPost.indexOf("<refund_id><![CDATA[") + 20, weixinPost.indexOf("<refund_id><![CDATA[") + 49);
//                    System.out.println(refund_id);
                    //保存退款返回的退款编号
                    OrderPay.saveRefundOrderCode(orderNo, ValidateUtil.isNull(fcOrderNo) ? orderNo : fcOrderNo, refund_id, ChannelUtils.wx);
                }
            } catch (Exception e) {
                System.out.println("截取退款编号失败");
                e.printStackTrace();
            }


            return true;

//            WXPayRefundResult refundResult = WeixinPay.getUnifiedorderResult(weixinPost);
//
//            if("SUCCESS".equalsIgnoreCase(refundResult.getResult_code())){
//                result = "200";
//                System.out.println("==========处理退款成功==========");
//            }else{
//                result = refundResult.getReturn_msg();
//            }
        }

        return false;
    }

    public static boolean refundPart(String appid, String mch_id, String apiKey,
                                     String certFilePath,
                                     String orderNo, String backOrderNo, double money, double refundMoney, boolean isUpdateOrderRefund) throws RequestFailException, DataEmptyException {
        String result = "";
        if (StringUtils.isEmpty(result)) {

            String nonce_str = RandCharsUtils.getRandomString(32);
            String out_refund_no = "T" + backOrderNo;

            int total_fee = CorrectYuan2Fen(money);//单位是分，即是0.01元
            int refund_fee = CorrectYuan2Fen(refundMoney);

            String op_user_id = mch_id;//操作员帐号, 默认为商户号

            SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
            parameters.put("appid", appid);
            parameters.put("mch_id", mch_id);
            parameters.put("nonce_str", nonce_str);
            parameters.put("out_trade_no", orderNo);
            parameters.put("out_refund_no", out_refund_no);
            parameters.put("total_fee", total_fee);
            parameters.put("refund_fee", refund_fee);
            parameters.put("op_user_id", op_user_id);

            String sign = WXSignUtils.createRefundSign(apiKey, "UTF-8", parameters);
            System.out.println("签名是：" + sign);

            WXPayRefund refund = new WXPayRefund();
            refund.setAppid(appid);
            refund.setMch_id(mch_id);
            refund.setNonce_str(nonce_str);
            refund.setOp_user_id(op_user_id);
            refund.setOut_refund_no(out_refund_no);
            refund.setRefund_fee(refund_fee);
            refund.setSign(sign);
            refund.setTotal_fee(total_fee);
            refund.setOut_trade_no(orderNo);

            //构造xml参数
            String xmlInfo = HttpXmlUtils.getRefundXmlInfo(refund);
            String wxUrl = WeixinConfig.refund_URL;
            String weixinPost = null;
            try {
                weixinPost = ClientCustomSSL.doRefund(wxUrl, xmlInfo, certFilePath, mch_id).toString();
            } catch (Exception e) {
                System.out.println("微信退款失败：" + e.getMessage());
                e.printStackTrace();
                return false;
            }
            System.out.println("微信退款：" + weixinPost);

            if (weixinPost.indexOf("<return_code><![CDATA[FAIL]]></return_code>") >= 0) {
                System.out.println(weixinPost);
                throw new RequestFailException("申请退款失败，请稍后再试 ");
            }
            if (weixinPost.indexOf("<result_code><![CDATA[FAIL]]></result_code>") >= 0) {
                try {
                    if (weixinPost.indexOf("<err_code_des><![CDATA[") >= 0) {
                        String msg = weixinPost.substring(weixinPost.indexOf("<err_code_des><![CDATA[") + 23, weixinPost.indexOf("]]></err_code_des>"));
                        throw new RequestFailException("订单：" + orderNo + "申请退款失败:" + msg);
                    }
                } catch (Exception e) {
                    System.out.println("截取退款失败原因失败" + e.getMessage());
//                    e.printStackTrace();
                }
                throw new RequestFailException("申请退款失败，请稍后再试！");
            }
            if (weixinPost.indexOf("ORDERNOTEXIST") >= 0 && weixinPost.indexOf("订单不存在") >= 0) {
                throw new DataEmptyException("订单不存在");
            }
            try {
                if (weixinPost.indexOf("<refund_id><![CDATA[") >= 0) {
                    String refund_id = weixinPost.substring(weixinPost.indexOf("<refund_id><![CDATA[") + 20, weixinPost.indexOf("<refund_id><![CDATA[") + 49);
                    //保存退款返回的退款编号
                    if (isUpdateOrderRefund) {
                        // 取消订单
                        OrderPay.saveRefundOrderCode(orderNo, orderNo, refund_id, ChannelUtils.wx);
                    } else {
                        OrderPay.savePartRefundOrderCode(orderNo, refund_id, ChannelUtils.wx);
                    }

                }
            } catch (Exception e) {
                System.out.println("截取退款编号失败");
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }


    public static boolean closeOrder(String orderNo) {

        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();

        parameters.put("appid", WeixinConfig.appid);

        parameters.put("mch_id", WeixinConfig.mch_id);

        parameters.put("out_trade_no", orderNo);//商户订单号，要唯一
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        String sign = null;      //签名
        try {
            sign = WXSignUtils.createSign(WeixinConfig.apiKey, "UTF-8", parameters);
        } catch (UnsupportedEncodingException e) {
            System.out.println("关闭微信订单时错误：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
        parameters.put("sign", sign);

//        String reuqestXml = PayCommonUtil.getRequestXml(parameters);
//        String    reuqestXml = new String(HttpXmlUtils.xmlInfo(unifiedorder).getBytes("UTF-8"), "UTF-8");
//        String    reuqestXml = HttpXmlUtils.toQueryXml(parameters);


        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("appid", WeixinConfig.appid);
        map.put("mch_id", WeixinConfig.mch_id);
        map.put("out_trade_no", orderNo);
        map.put("nonce_str", str);
        map.put("sign", sign);
        String reuqestXml = HttpXmlUtils.toQueryXml(map);
//        String result = CommonUtil.httpsRequest(ConfigUtil.CHECK_ORDER_URL, "POST", reuqestXml);
        String url = "https://api.mch.weixin.qq.com/pay/closeorder";
        String method = "POST";
        String json = HttpXmlUtils.httpsRequest(url, method, HttpXmlUtils.toQueryXml(map)).toString();
        System.out.println(json);
//
//        Map<String, String> map = XMLUtil.doXMLParse(result);
//
//        String returnCode = map.get("return_code");
//
//        String resultCode = map.get("result_code");
//
//        if (returnCode.equalsIgnoreCase("SUCCESS") && resultCode.equalsIgnoreCase("SUCCESS")) {
//
//            //TODO 关闭订单成功的操作
//
//            System.out.println("订单关闭成功");
//
//        } else {
//
//            //TODO 关闭订单失败的操作
//
//        }
        return true;
    }


    //--------------------------

    public static String testCA() {
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("mch_id", WeixinConfig.mch_id);
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        String sign = null;      //签名
        try {
            sign = WXSignUtils.createCADemoSign("UTF-8", parameters);
        } catch (Exception e) {
            System.out.println("demno错误：" + e.getMessage());
            e.printStackTrace();
            return e.getMessage();
        }

        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("mch_id", WeixinConfig.mch_id);
        map.put("nonce_str", str);
        map.put("sign", sign);
        String reuqestXml = HttpXmlUtils.toQueryXml(map);
        String url = "https://apitest.mch.weixin.qq.com/sandboxnew/pay/getsignkey";
        String method = "POST";
        String json = HttpXmlUtils.httpsRequest(url, method, reuqestXml).toString();
        System.out.println(json);
        return json;
    }

    //测试
    public static void main(String[] args) throws Exception {
        //测试支付
//        String xml = WeixinPayUtils.getInstance().mobile_direct_pay("2018080905", 1, 30, "商品", "商品详情");
//        String xml = WeixinPayUtils.getInstance().winxin_pay_gzh("o1bU_1iu1UhuSCF77XGtZLxg76ho", "201712018001100", 0.01f, 30, "商品", "商品详情");

//        String xml = WeixinPayUtils.getInstance().mobile_direct_pay("201712018001100", 0.01f, 30, "商品", "商品详情");
//        String xml = WeixinPayUtils.getInstance().winxin_pay_gzh("oXrYT1FVVEFTtnVoIDJkegn-YtLo", "18030514238132671", 0.01f, 30, "商品", "商品详情");
//        String xml = WeixinPayUtils.getInstance().winxin_pay_xcx("o7aT30GlY4288aNDRM-dkTziFLOM", "18030514238132671", 0.01f, 30, "商品", "商品详情");
//        String xml = WeixinPayUtils.getInstance().winxin_ewm_pay("1712092033273853", 0.01f, 30, "商品", "商品详情");
//        String xml = WeixinPayUtils.getInstance().winxin_pay_wap("1712092033273853", 0.01f, 30, "商品", "商品详情");
//        String xml = WeixinPayUtils.getInstance().winxin_pay_wap2("127.0.0.1", "171220920331273853", 0.01f, 30, "商品", "商品详情");
//        System.out.println(xml);

        //测试查询
//        System.out.println(DateUtils.getCurrTime() + ":" + WeixinPayUtils.getInstance().query_pay_trade("", "1803062215384993"));
//        System.out.println(DateUtils.getCurrTime() + ":" + WeixinPayUtils.getInstance().getWxPayStatus("", "1710091850328685"));
//        System.out.println(DateUtils.getCurrTime() + ":" + WeixinPayUtils.getInstance().getWxPayStatus("", "wx_xcx","1803062215384993"));

//        QueryResult queryResult = WeixinPayUtils.getInstance().getWxPayStatus("", "wx_xcx", "1803062316139461");
//        System.out.println(queryResult.getPayStatus());
//        System.out.println(queryResult.isQuerySuccess());


//        System.out.println(WeixinPayUtils.getInstance().mobile_refund("1703192038464221", 1f));

//        WeixinPayUtils.getInstance().refund("1712010954112003", 0.01d, 0.01d);


//        WeixinPayUtils.getInstance().closeOrder("1803012135158892");

//        String weixinPost = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg><appid><![CDATA[wx4687acd8c1b24f10]]></appid><mch_id><![CDATA[1505708181]]></mch_id><nonce_str><![CDATA[d6IvcNF2QMjP2BDk]]></nonce_str><sign><![CDATA[939847170AF658C3DBC7B9D175ECA1C7]]></sign><result_code><![CDATA[FAIL]]></result_code><err_code><![CDATA[NOTENOUGH]]></err_code><err_code_des><![CDATA[基本账户余额不足，请充值后重新发起]]></err_code_des></xml>";
//        System.out.println();
//        System.out.println(weixinPost.indexOf("<err_code_des><![CDATA["));
//        int len = weixinPost.indexOf("]]></err_code_des>") - weixinPost.indexOf("<err_code_des><![CDATA[") - 23;
//        int len2 = weixinPost.indexOf("<err_code_des><![CDATA[") + 23;
//        System.out.println(len);
//        System.out.println(len2);
//        String msg = weixinPost.substring(weixinPost.indexOf("<err_code_des><![CDATA[") + 23, weixinPost.indexOf("]]></err_code_des>"));
//        System.out.println(msg);


//        System.out.println(new Float(Float.parseFloat(18.3 + "") * 100).intValue());
//        System.out.println(new Float(0.0013d * 100).intValue());
//        System.out.println((int) (18.3 * 100));


        System.out.println(CorrectYuan2Fen(40.6));
    }


    //正确的元转分方式
    public static Integer CorrectYuan2Fen(Double yuan) {
        //（重点）Double直接转BigDecimal丢失精度，此处需要将Double转换为String
        return new BigDecimal(String.valueOf(yuan)).movePointRight(2).intValue();
    }


    /*
    鲸至用的这个
     * 微信手机直接支付
     * Jahnke 2017年1月8日 08:15:19
     * @param orderCode
     * @param pay
     * @param activeTime
     * @param subject
     * @param body
     * @return
     */
    public String winxin_pay_wap2(String ip, String orderCode, double pay, int activeTime, String subject, String body) {
        //参数：开始生成签名
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", WeixinConfig.appid);
        parameters.put("mch_id", WeixinConfig.mch_id);
        parameters.put("notify_url", WeixinConfig.notify_url);
        parameters.put("body", subject == null || subject.equals("") ? "商品" : subject);
        String str = RandCharsUtils.getRandomString(16);
        parameters.put("nonce_str", str);
        parameters.put("detail", body == null || body.equals("") ? "商品" : body);
        parameters.put("attach", "备用参数");
        parameters.put("out_trade_no", orderCode);
//        parameters.put("total_fee", new Float(pay * 100).intValue());        //单位是分，即是0.01元
        parameters.put("total_fee", CorrectYuan2Fen(pay));        //单位是分，即是0.01元
        String time_start = RandCharsUtils.timeStart();
        String time_expire = RandCharsUtils.timeExpire(30);
        parameters.put("time_start", time_start);       //订单交易时间
        parameters.put("time_expire", time_expire);     //订单逾期时间
        String trade_type = "MWEB";
        parameters.put("trade_type", trade_type);
        parameters.put("spbill_create_ip", ip);        //支付的客户端IP地址
        String sign = null;
        try {
            sign = WXSignUtils.createSign(WeixinConfig.apiKey, "UTF-8", parameters);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.out.println("获取微信签名错误：" + e.getMessage());
        }

        Unifiedorder unifiedorder = new Unifiedorder();
        unifiedorder.setAppid(WeixinConfig.appid);
        unifiedorder.setAttach(parameters.get("attach").toString());
        unifiedorder.setBody(parameters.get("body").toString());
        unifiedorder.setDetail(parameters.get("detail").toString());
        unifiedorder.setMch_id(WeixinConfig.mch_id);
        unifiedorder.setNonce_str(parameters.get("nonce_str").toString());
        unifiedorder.setNotify_url(WeixinConfig.notify_url);
        unifiedorder.setOut_trade_no(orderCode);
        unifiedorder.setSign(sign);
        unifiedorder.setSpbill_create_ip(parameters.get("spbill_create_ip").toString());
        unifiedorder.setTime_expire(time_expire);
        unifiedorder.setTime_start(time_start);
//        unifiedorder.setTotal_fee(new Float(pay * 100).intValue());
        unifiedorder.setTotal_fee(CorrectYuan2Fen(pay));
        unifiedorder.setTrade_type(trade_type);

        //构造xml参数
        String xmlInfo = null;
//        xmlInfo = new String(HttpXmlUtils.xmlInfo(unifiedorder).getBytes("UTF-8"), "ISO-8859-1");
        try {
            xmlInfo = new String(HttpXmlUtils.xmlInfo(unifiedorder).getBytes("UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.out.println("微信H5支付错误：" + e.getMessage());
        }

        String wxUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String method = "POST";
        String weixinPost = HttpXmlUtils.httpsRequest(wxUrl, method, xmlInfo).toString();

        if (weixinPost.indexOf("<return_code><![CDATA[FAIL]]></return_code>") >= 0) {
            System.out.println(weixinPost);
            System.out.println("获取签名失败，请稍后再试 ");

        }
        if (weixinPost.indexOf("商户订单号重复") >= 0) {
            System.out.println("商户订单号重复 " + orderCode);
        }
        //二次签名
        String prepayid = weixinPost.substring(weixinPost.indexOf("<prepay_id>") + 20, weixinPost.indexOf("</prepay_id>") - 3);

        SortedMap<Object, Object> parameters02 = new TreeMap<Object, Object>();
        parameters02.put("appid", WeixinConfig.appid);
        parameters02.put("partnerid", WeixinConfig.mch_id);
        parameters02.put("package", "Sign=WXPay");
        long time = Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10));
//        System.out.println("time:" + time);
        parameters02.put("timestamp", time);
        parameters02.put("noncestr", str);
        parameters02.put("prepayid", prepayid);
        String sign2 = null;
        try {
            sign2 = WXSignUtils.createSign(WeixinConfig.apiKey, "UTF-8", parameters02);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.out.println("H5支付，二次签名错误：" + e.getMessage());
        }
        System.out.println(sign2);
        parameters02.put("sign", sign2);
        String mweb_url = weixinPost.substring(weixinPost.indexOf("<mweb_url>") + 19, weixinPost.indexOf("</mweb_url>") - 3);
        parameters02.put("mweb_url", mweb_url);
//        System.out.println(URLEncoder.encode(mweb_url));
        return JSONObject.fromObject(parameters02).toString();
    }


}
